<?php
/**
 * User: 784855684@qq.com
 * Date: 31/12/2017
 * Time: 17:30
 */
declare(strict_types=1);


namespace AppBundle\Utils;


use AppBundle\Entity\Material;
use AppBundle\Throwable\MaterialInUseException;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\EntityManager;

class MaterialUtil extends EntityUtil
{

    /**
     * @param string $title
     * @param string $description
     * @param float $price
     * @param int $inventory
     * @param bool $autoFlush
     * @return Material
     */
    public function create(string $title, string $description, float $price, int $inventory = 0, bool $autoFlush = true)
    {
        $material = new Material();

        $material->setName($title);
        $material->setInventory($inventory);
        $material->setPrice($price);
        $material->setDescription($description);

        $material->setRemove(0);
        $material->setUniqueCode(self::createGUID('MT'));
        $material->setAddTime(new \DateTime());
        $this->em->persist($material);
        $autoFlush and $this->em->flush();
        return $material;
    }

    /**
     * @param Material $material
     * @param bool $autoFlush
     * @return void
     * @throws MaterialInUseException
     */
    public function remove(Material $material, bool $autoFlush = true)
    {
        if (count($material->getProducts())) {
            throw new MaterialInUseException($material->getName());
        }
        $material->setRemove(1);
        $autoFlush and $this->em->flush();
    }

    /**
     * @param string $prefix
     * @return string
     */
    public static function createGUID($prefix = ''): string
    {
        $str = md5(uniqid((string)mt_rand(), true));
        $uuid = substr($str, 0, 8) . '-';
        $uuid .= substr($str, 8, 4) . '-';
        $uuid .= substr($str, 12, 4) . '-';
        $uuid .= substr($str, 16, 4) . '-';
        $uuid .= substr($str, 20, 12);
        return strtoupper($prefix . $uuid);
    }

}